<template>
  <text x="0" y="0" ref="text">
    <template v-if="tspan.marks && !initPosition">
      <tspan
        class="opacity"
        v-for="(i, index) in tspan.marks"
        :x="tspan.x"
        :y="tspan.y"
        :key="index"><tspan :class="'prev' + index">{{ getMarkTextPrev(i.start) }}</tspan><tspan :class="'mark' + index">{{ getMarkText(i.start, i.end) }}</tspan></tspan>
    </template>
    <tspan :data-span-start="tspan.start" :x="tspan.x" :y="tspan.y">{{ tspan.type === 'empty' ? ' ' : tspan.text }}</tspan>
  </text>
</template>

<script>
export default {
  props: {
    tspan: Object
  },

  data () {
    return {
      initPosition: false
    }
  },

  watch: {
    tspan () {
      this.initPosition = false
      // nextTick 确保 marks 元素被重新渲染完成
      this.$nextTick(() => {
        this.getPosition()
      })
    }
  },

  methods: {
    getMarkTextPrev (mStart) {
      let start = mStart - this.tspan.start
      if (start < 0) {
        return ''
      } else {
        return this.tspan.text.slice(0, start)
      }
    },
    getMarkText (mStart, mEnd) {
      let start = mStart - this.tspan.start
      const end = mEnd - this.tspan.start + 1
      // 起始位置最小从 0 开始
      if (start < 0) start = 0
      return this.tspan.text.slice(start, end)
    },
    getPosition () {
      if (!this.tspan.marks) return
      const textEl = this.$refs.text
      this.tspan.marks.forEach((i, index) => {
        const prevEl = textEl.querySelector('.prev' + index)
        const markEl = textEl.querySelector('.mark' + index)
        i.x = this.tspan.x + prevEl.getBoundingClientRect().width
        i.y = this.tspan.y
        i.width = markEl.getBoundingClientRect().width
        this.$emit('push-mark', i)
      })
      // 获取位置完毕可以隐藏元素
      this.initPosition = true
    }
  },

  mounted () {
    this.getPosition()
  }
}
</script>

<style>

</style>